/**
 * @author DongPing
 * 2022/1/4 16:03
 *
 * 根据元模型metas和数据 显示表格
 *
 * */
import {Table} from "antd";
import { formatMessage } from '@/utils/i18n-transform';
import {ExtBtn} from "@/components/SelfIcon";
import components from '@/components/schema-form-render/schema-components-registed/components-biz';

export function DisplayTableByMetas<T>(props: {
	// 表格列的元模型配置项
	metas: any[],
	data: T[],

	// 进行了某些操作之后刷新页面数据
	onRefresh?: () => void,

	// 操作列的metas
	operationMetas?: any[],
	// 操作按钮回调 如果返回的promise的值为true，操作完成之后刷新页面
	operationCallbacks?: {[name: string] : (record: T) => (void | Promise<boolean>)},

	// 渲染操作列的方法，如果这个参数存在，忽略operationMetas参数
	renderOperations?: (record: T) => any,

	// 表格里面编辑了值
	onDataChange?: (data: T[]) => void
}) {
	function defaultOnRefresh() {}
	const {metas, data, onRefresh = defaultOnRefresh, operationMetas = [], operationCallbacks = {}, renderOperations} = props;
	return (
		<Table scroll={{x: 'max-content'}} size={"small"} pagination={false} dataSource={data as unknown as object[]}>
			<Table.Column fixed title={formatMessage({ id: 'config.common.label.seq' })} render={(t, r: T, index) => index + 1}/>
			{
				renderOperations ? <Table.Column fixed title={formatMessage({ id: 'config.common.label.operation' })} render={(t,r:T) => {
					return renderOperations(r);
				}} /> : null
			}
			{
				(!renderOperations && (operationMetas.length > 0)) ?
					<Table.Column fixed title={formatMessage({ id: 'config.common.label.operation' })} render={(t, r: T) => {
						return (
							<>
								{operationMetas.map((opt) => {
									return (
										<ExtBtn key={opt.key} icon={opt.key} onClick={() => {
											const callback = operationCallbacks[opt.props.hook];
											if(typeof callback === 'function') {
												const res = callback(r);
												if(res) {
													res.then((shouldRefresh) => shouldRefresh ? onRefresh() : null)
												}
											}
										}}/>
									)
								})}
							</>
						)
					}}/>
					:
					null
			}

			{
				metas.map((meta: any) => (
					<Table.Column
						title={meta.label}
						key={meta.key}
						dataIndex={meta.key}
						render={(t, r: any) => {
							if(meta.props.inputValueComponentType) {
								const C = components[meta.props.inputValueComponentType];
								if(C) {
									return <C {...meta.props.attributes} value={t} onChange={(newValue: any) => {
										r[meta.key] = newValue;
										props.onDataChange && props.onDataChange([...props.data]);
									}}/>
								}

							}
							if(meta.props.columnRenderType === 'DICT_TYPE') {
								return <span>{r[meta.key + 'Name']}</span>
							}
							return <span>{t}</span>
						}}
					/>
				))
			}
		</Table>
	)
}
